package com.dodo.blog.ui.page;

import com.dodo.blog.ui.component.container.Body;
import com.dodo.blog.ui.component.container.H1;
import com.dodo.blog.ui.component.container.H2;
import com.dodo.blog.ui.component.container.Html;
import com.dodo.blog.ui.component.container.Panel;
import com.dodo.blog.ui.component.container.Paragraph;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public class ErrorPage
        extends Page
{
    private static final long serialVersionUID = 1L;

    private Throwable throwable;

    public void setError( Throwable throwable )
    {
        this.throwable = throwable;
    }

    private Body body = new Body();

    private Html html = new Html();

    @Override
    public String getPageContent()
    {
        return html.render().toString();
    }

    @Override
    public void onRender()
    {
        html.add( body );

        H1 h1 = new H1( "Error occurred" );
        h1.setAttribute( "style", "color: #fff; background: #a00;padding: 10px;" );
        body.add( h1 );

        String err;
        if ( throwable instanceof InvocationTargetException )
        {
            err = throwable.getCause().toString();
        }
        else
        {
            err = throwable.toString();
        }

        Panel stackWrapper = new Panel();
        stackWrapper.setAttribute( "style", "border: 1px solid #a00;margin: 0;padding: 10px;" );
        body.add( stackWrapper );

        H2 cause = new H2( err );
        cause.setAttribute( "style", "color: #a00; 10px;border-bottom: 1px solid #a00;font-weight: bold;" );
        stackWrapper.add( cause );

        StringWriter sw = new StringWriter();
        throwable.printStackTrace( new PrintWriter( sw ) );

        Paragraph stack = new Paragraph( sw.toString().replace( "\n", "<br/>" ).replace( "\t", "<span>&nbsp;&nbsp;&nbsp;<span>" ) );
        stack.setAttribute( "style", "margin: 0; padding: 0;color: #555;" );
        stackWrapper.add( stack );
    }
}